//
//  BKJLocationService.m
//  BKJ
//
//  Created by 吴涛 on 16/4/11.
//  Copyright © 2016年 贝壳家iOS. All rights reserved.
//
#import <CoreLocation/CoreLocation.h>
#import "BKJLocationService.h"

@interface BKJLocationService ()<CLLocationManagerDelegate>

@property (nonatomic, strong) CLGeocoder *geocoder;

@end


@implementation BKJLocationService


+ (instancetype)shareService{
  static BKJLocationService *manager;
  
  static dispatch_once_t onceToken;
  
  dispatch_once(&onceToken, ^{
    manager = [[BKJLocationService alloc] init];
  });
  
  return manager;
}


- (instancetype)init{
  if (self = [super init]) {    
    [self.locationManager startUpdatingLocation];
  }
  return self;
}


#pragma mark - CLLocationManagerDelegate


-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
  
  
  CLLocation *location = [locations firstObject];//取出第一个位
  
  @weakify(self)
  [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
    
    dispatch_async(dispatch_get_main_queue(), ^{
      
      @strongify(self)
      if (error != nil) {
        
        NSLog(@"%@",error.description);
        
      }else{
        if (placemarks.count > 0) {
          
          CLPlacemark *mark = placemarks.firstObject;
          if (![self.adress isEqualToString:mark.name]) {
              self.currentLocation = location;
              self.adress = mark.name;
          }
  
        }

      }
      
      
    });
    
  }];
  
  [self.locationManager stopUpdatingLocation];
  
}


- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
  if (error != nil) {
    self.adress = @"定位失败";
  }
}





#pragma mark - getter




- (CLLocationManager *)locationManager{
  if (!_locationManager) {
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    _locationManager.pausesLocationUpdatesAutomatically = YES;
    _locationManager.headingFilter = kCLHeadingFilterNone;
    [_locationManager requestWhenInUseAuthorization];
    
  }
  return _locationManager;
}

//- (CLLocation *)currentLocation{
//  if (!_currentLocation) {
//    _currentLocation = [CLLocation new];
//  }
//  return _currentLocation;
//}

- (CLGeocoder *)geocoder{
  if (!_geocoder) {
    _geocoder = [CLGeocoder new];
  }
  return _geocoder;
}





@end
